package com.springcloud.gateway.filter;

import com.springcloud.gateway.provider.AuthProvider;
import com.springcloud.gateway.provider.RequestProvider;
import com.springcloud.gateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/10/31 16:33
 * @description
 * @Modify By：
 * @ModifyTime： 2019/10/31
 * @Modify marker：
 **/
@Slf4j
//@RequiredArgsConstructor 会生成一个包含常量，和标识了Notnull的变量构造方法
@RequiredArgsConstructor
@Configuration
//@ConditionalOnProperty 来控制Configuration是否生效
@ConditionalOnProperty(value = "gateway.log.request.enabled", havingValue = "true", matchIfMissing = true)
public class GlobalRequestLogFilter implements GlobalFilter, Ordered {
    private final WebEndpointProperties endpointProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //打印请求的路径
        String path = request.getPath().pathWithinApplication().value();

        log.info("path:{}", path);
        //忽略endpoint 请求

        String endpointBasePath = endpointProperties.getBasePath();
        log.info("endpointBasePath:{}", endpointBasePath);
        //startWith 如果字符串以指定的前缀开始，则返回true;
        if (StringUtils.isNotBlank(endpointBasePath) && path.startsWith(endpointBasePath)) {
            return chain.filter(exchange);
        }

        //获取原始URL
        String requestUrl = RequestProvider.getOriginalRequesetUrl(exchange);
        //构建一条长日志，避免并发下日志错乱
        //使用StringBuffer 高并发情况下保证安全 synchronized
        StringBuffer beforeReqLog = new StringBuffer(300);
        //日志参数
        List<Object> beforeReqArgs = new ArrayList<>();
        beforeReqLog.append("\n\n================= GateWay Request Start =====================\n");
        //打印路由
        beforeReqLog.append("=============>{}:{}\n");
        //参数
        String requestMethod = request.getMethodValue();
        beforeReqArgs.add(requestMethod);
        beforeReqArgs.add(requestUrl);

        //打印请求头
        HttpHeaders headers = request.getHeaders();
        headers.forEach((headerName, headerValue) -> {
            beforeReqLog.append("=====headers======{}:{}\n");
            beforeReqArgs.add(headerName);
            if(AuthProvider.AUTH_KEY.toLowerCase().equals(headerName)){
                String value= headerValue.get(0);
                String token= JwtUtil.getToken(value);
                Claims claims =JwtUtil.parseJWT(token);
                //此处省略JWTtoken
                beforeReqArgs.add(claims.toString());
                beforeReqLog.append("=====Headers======{};{}\n");
                beforeReqArgs.add(headerName.concat("-original"));
                beforeReqArgs.add(StringUtils.join(headerValue));
            }else{
                beforeReqArgs.add(StringUtils.join(headerValue));
                //join 将数组变成字符串
            }
        });
        beforeReqLog.append("===================== Gateway Request End============\n");
        log.info(beforeReqLog.toString(), beforeReqArgs.toArray());
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
